package com.bazaaroid.mobile.android;

import java.util.ArrayList;

import com.bazaaroid.mobile.android.adapter.ProductsAdapter;
import com.bazaaroid.mobile.android.db.DbBazaaAdapter;
import com.bazaaroid.mobile.db.model.partner.Product;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TwoLineListItem;

public class SearchResult extends ListActivity {

	boolean mOffline = true;
	private ListView lv1;
	private String lv_arr[] = null;//{"Android","iPhone","BlackBerry","AndroidPeople"};	
	private String TAG = "[SearchResult]";
	
	private DbBazaaAdapter dbBazaaAdapter = null;
	private String mQuery = null;
	private ArrayList<Product> mSearchResult = null;
	private ProductsAdapter mProductsAdapter = null;
	private Runnable viewResults = null;
	private ProgressDialog mProgressDialog = null;	
	private ListView mListViewResults = null;
	
	public SearchResult() {
		// TODO Auto-generated constructor stub
		Log.d(TAG, "C-tor...");
	}


	@Override
	public void onCreate(Bundle result)
	{
		Log.d(TAG, "onCreate....");
		super.onCreate(result);
		
		dbBazaaAdapter = new DbBazaaAdapter(this);
		mListViewResults = new ListView(this);
		
		Bundle extras = getIntent().getExtras();
		/*ArrayList<String> searchResult = null;*/
		if(extras !=null)
		{
			//mSearchResult/*searchResult*/ = extras.getStringArrayList("searchResult");
			mQuery = extras.getString("query");
		}
		
		//Log.d(TAG, String.format("Retrieved number of items: %d", searchResult.size()));
		Log.d(TAG, String.format("Received query string: '%s'", mQuery));
		
		/*setContentView(R.layout.search_result);
		lv1=(ListView)findViewById(R.id.SearchResults);
		// By using setAdpater method in listview we an add string array in list.
		lv_arr = new String[searchResult.size()];//(String[])searchResult.toArray();
		for(int i = 0; i < searchResult.size(); ++i)
		{
			lv_arr[i] = searchResult.get(i);
		}
		
		lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));*/
		
		
		mSearchResult = new ArrayList<Product>();
		
		this.mProductsAdapter = new ProductsAdapter(this, R.layout.products_row, mSearchResult);
		try
		{
			setListAdapter(this.mProductsAdapter);
            //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
			
			
			
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
       
        viewResults = new Runnable(){
            @Override
            public void run() {
            	getSearchResults();
            }
        };
        Thread thread =  new Thread(null, viewResults, "MagentoBackground");
        thread.start();
        mProgressDialog = ProgressDialog.show(this, getString(R.string.search_please_wait), getString(R.string.search_retrieving), true);
        
        //getListView().setOnItemClickListener(listlistener);
        mListViewResults = getListView();
        mListViewResults.setOnItemClickListener(listlistener);
	}
	
	private void getSearchResults()
	{
		try
		{
			Log.d(TAG, String.format("Running a query: '%s'", mQuery));
			
			mSearchResult = doSearch(mQuery);
			
			Log.d(TAG, String.format("Find %d items.", mSearchResult.size()));
			
			for(int i = 0; i < mSearchResult.size(); ++i)
			{
				Log.d(TAG, String.format("%d: %s", i, mSearchResult.get(i).getName()));
			}
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
		runOnUiThread(returnRes);
	}
	
	private ArrayList<Product> doSearch(String query)
	{
		if(mOffline)
		{
			ArrayList<Product> searchResult = dbBazaaAdapter.doQueryProducts(mQuery);
			return new ArrayList<Product>(searchResult);
		}
		else
		{
			//TODO: search using XML API
			return new ArrayList<Product>();
		}
	}
	
	private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if(mSearchResult != null && mSearchResult.size() > 0){
                mProductsAdapter.notifyDataSetChanged();
                for(int i=0;i<mSearchResult.size();i++)
                mProductsAdapter.add(mSearchResult.get(i));
                /*if(mProductsAdapter.getCount() > 0)
                {
        			mListViewResults = (ListView)findViewById(R.id.SearchResults);
        			mListViewResults.setOnItemClickListener(mProductsAdapter);
                }*/
            }
            mProgressDialog.dismiss();
            mProductsAdapter.notifyDataSetChanged();
        }
      };
      
	  private OnItemClickListener listlistener = new OnItemClickListener() {

		  @Override
		  public void onItemClick(AdapterView<?> parent, View view, int position, long row_id) 
		  {
			  Toast.makeText(getApplicationContext(), getString(R.string.search_cliked_value) + 
		  			((Product)parent.getItemAtPosition(position)).getName(), Toast.LENGTH_SHORT).show();
			  // TODO: Click on item should issue an request for the item locations (if not provided).
			  // When received, display the locations on the map
			  Product product = (Product)parent.getItemAtPosition(position);
			  
		  }
	  };
    	        
}
